package T5_why_synchronized_Right;

public class Why_synchronized_Right {    
    public static void main(String[] args) {    
    	Foo foo = new Foo();   
    	MyThread r = new MyThread(foo);    
        Thread ta = new Thread(r, "Thread-A");    
        Thread tb = new Thread(r, "Thread-B");    
        
        ta.start();    
        tb.start();    
    }    
}  

class MyThread implements Runnable {
	public MyThread(Foo foo){
		this.foo = foo;
	}
//	public synchronized void run() {    
	public  void run() {    
        for (int i = 0; i < 3; i++) {    
        	for(int j=0;j<10000000;j++);
        	synchronized(this){  //must put a synchronized in here
        		foo.fix(30);    
        		System.out.println(Thread.currentThread().getName() + " x = " + foo.getX());    //when it reads x the lock was is unlock
        	}  
        }
    }    
	private Foo foo = null; 
}

class Foo {    
    private int x = 100;   
    public int getX() {    
        return x;    
    }    
    public int fix(int y) {    
//    	for(int i=0;i<10;i++) { 
//			for(int j=0;j<10000;j++);
//			System.out.print(" " + i); 
//		} 
//    	System.out.println("  end "); 
        x = x - y;    
        return x;    
    }    
}  
